<script lang="ts" setup>
import { ref, onMounted, reactive, onUnmounted, nextTick } from 'vue';
import { Search } from '@vben/icons';
import { getCertificationInfoByConditionWithKeywordApi } from '#/api/certificate/certificatesMgr';

import { trimStringParams } from '#/utils/trimStringParams';

const orgTree = ref<any[]>([])
const treeRef = ref()
const searchKeyword = ref('')
const currentNode = ref()
const total = ref(0)
const pageData = reactive({
  curPage: 1,
  pageSize: 10
})
const tableLoading = ref(0);

// 加载相关状态
const isLoading = ref(false)
const hasMore = ref(false)
const scrollContainer = ref<HTMLElement>()
const loadMoreTrigger = ref<HTMLElement>()
const isInitialized = ref(false) // 添加初始化状态
const isLoadMoreTriggered = ref(false) // 防止重复触发

// 默认展开的节点ID数组
const defaultExpandedKeys = ref<string[]>([])

const treeProps = { children: 'children', label: 'name', isLeaf: 'isLeaf' }

const fileTree = () => { // 搜索
  // 重置分页状态
  pageData.curPage = 1
  orgTree.value = []
  hasMore.value = false
  isInitialized.value = false
  isLoadMoreTriggered.value = false
  getTreeData()
}

// 递归处理组织树数据
const processOrgTreeData = (data: any[]): any[] => {
  if (!data || !Array.isArray(data)) {
    return []
  }
  
  return data.map((item: any) => {
    const processedItem = {
      ...item,
      id: item.orgId || item.id,
      name: item.orgName || item.name,
      children: processOrgTreeData(item.children)
    }
    return processedItem
  })
}

const getTreeData = async (isLoadMore = false) => { // 获取组织树
  const name = trimStringParams(searchKeyword.value)
  const params = {
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  } as any;
  if (name) {
    params.name = name
  }
  
  if (isLoadMore) {
    isLoading.value = true
  } else {
    tableLoading.value = 1
  }
  
  try {
    const res = await getCertificationInfoByConditionWithKeywordApi(params)
    const { data, pageInfo } = res;
    const processedData = processOrgTreeData(data)
    
    if (isLoadMore) {
      // 上拉加载时，合并数据
      orgTree.value = [...orgTree.value, ...processedData]
    } else {
      // 首次加载或搜索时，替换数据
      orgTree.value = processedData
    }
    
    total.value = pageInfo.totalRows;
    
    // 检查是否还有更多数据
    hasMore.value = orgTree.value.length < total.value
    
    // 标记已初始化
    isInitialized.value = true
    
    // 重置触发状态
    isLoadMoreTriggered.value = false

    // 设置默认展开的节点（仅在首次加载时）
    if (!isLoadMore && data && data.length > 0) {
      setTimeout(() => {
        const {id} = data[0]
        defaultExpandedKeys.value = [id]
      }, 0)
      if (data[0]?.children?.length > 0) {
        const {children} = data[0]
        currentNode.value = children[0].orgId
        treeRef.value.setCurrentKey(children[0].orgId)
        emit('queryCert', { certifiedId: children[0].certId, id: children[0].orgId })
      }
    }
    
    // 检查是否需要自动加载更多（当内容高度小于容器高度时）
    nextTick(() => {
      checkAndAutoLoadMore()
    })
  } catch (error) {
    console.error('获取组织树数据失败:', error)
    // 重置触发状态
    isLoadMoreTriggered.value = false
  } finally {
    if (isLoadMore) {
      isLoading.value = false
    } else {
      tableLoading.value = 0;
    }
  }
}

// 检查并自动加载更多数据
const checkAndAutoLoadMore = () => {
  if (!scrollContainer.value || !treeRef.value) return
  
  const containerHeight = scrollContainer.value.clientHeight
  const treeHeight = treeRef.value.$el.scrollHeight
  
  // 如果树的高度小于容器高度，且还有更多数据，自动加载
  if (treeHeight < containerHeight && hasMore.value && !isLoading.value && !isLoadMoreTriggered.value) {
    // 内容高度不足，自动加载更多数据
    loadMore()
  }
}

// 防抖的高度检查函数
let heightCheckTimer: any = null
const debouncedHeightCheck = () => {
  if (heightCheckTimer) {
    clearTimeout(heightCheckTimer)
  }
  heightCheckTimer = setTimeout(() => {
    checkAndAutoLoadMore()
  }, 100)
}

// 窗口大小变化监听
const handleResize = () => {
  debouncedHeightCheck()
}

// 上拉加载更多
const loadMore = async () => {
  // 多重检查，确保不会重复加载
  if (isLoading.value || !hasMore.value || !isInitialized.value || isLoadMoreTriggered.value) {
    return
  }
  
  // 设置触发状态，防止重复触发
  isLoadMoreTriggered.value = true
  isLoading.value = true
  
  try {
    pageData.curPage++
    await getTreeData(true)
  } catch (error) {
    // 如果加载失败，回退页码
    pageData.curPage--
  } finally {
    isLoading.value = false
  }
}

// 使用 Intersection Observer 监听加载触发器
let observer: IntersectionObserver | null = null

const setupIntersectionObserver = () => {
  if (!loadMoreTrigger.value) return
  
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        // 只有在已初始化、有更多数据、不在加载中、未触发时才触发
        if (entry.isIntersecting && 
            hasMore.value && 
            !isLoading.value && 
            isInitialized.value && 
            !isLoadMoreTriggered.value) {
          loadMore()
        }
      })
    },
    {
      root: scrollContainer.value,
      rootMargin: '100px', // 提前100px触发
      threshold: 0.1
    }
  )
  
  observer.observe(loadMoreTrigger.value)
}

const handleNodeClick = (node: any) => {
  console.log(node)
  if (node.orgId && node.certId) {
    emit('queryCert', { certifiedId: node.certId, id: node.id })
  }
}

onMounted(() => {
  getTreeData()
  
  // 设置 Intersection Observer
  nextTick(() => {
    setupIntersectionObserver()
  })
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理 Intersection Observer
  if (observer) {
    observer.disconnect()
  }
  
  // 清理窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 清理定时器
  if (heightCheckTimer) {
    clearTimeout(heightCheckTimer)
  }
})

const emit = defineEmits(['queryCert'])

</script>
<template>
  <section v-loading="tableLoading" class="flex flex-col h-full">
    <div class="text-[16px] leading-[24px] text-[#191919] mb-[10px] font-500">{{ $t('common.groupTxt') }}</div>
    <el-input v-model="searchKeyword" @change="fileTree" class="w-[100%] mb-[10px]"
      :placeholder="$t('common.inputPhTxt', [$t('common.keywordsTxt')])">
      <template #suffix>
        <Search class="size-5 cursor-pointer" @click="fileTree"></Search>
      </template>
    </el-input>
    
    <!-- 树形组件容器 -->
    <div class="flex-1 overflow-auto relative" ref="scrollContainer">
      <el-tree 
        ref="treeRef" 
        @node-click="handleNodeClick" 
        :accordion="true" 
        :data="orgTree" 
        :props="treeProps" 
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys" 
        :highlight-current="true" 
        class="text-[14px]"
      >
        <template #default="{ data }">
          <div class="w-full truncate" :title="data.name">{{data.name}}</div>
        </template>
      </el-tree>
      
      <!-- 加载更多触发器 -->
      <div ref="loadMoreTrigger" class="h-4"></div>
      
      <!-- 加载更多状态 -->
      <div v-if="isLoading" class="flex items-center justify-center py-4 text-gray-500 text-sm">
        <div class="loading-spinner mr-2"></div>
      </div>
      
      <!-- 没有更多数据提示 -->
      <div v-if="!hasMore && orgTree.length > 0 && pageData.curPage > 1" class="flex items-center justify-center py-4 text-gray-400 text-sm">
        {{ $t('common.noMoreData') }}
      </div>
    </div>
    
  </section>
</template>

<style scoped>
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
:deep(.el-tree-node__content) {
  height: 32px;
  border-radius: 4px;
  line-height: 32px;
  margin-bottom: 8px;
  color: #191919;
}
:deep(.is-current>.el-tree-node__content) {
  background-color: #CCE1F6;
  border-radius: 4px;
  font-weight: 500;
  color: #0067D1;
}
</style>
